package com.ecommerce.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.List;

@RestController
@RequestMapping("/api/test")
@CrossOrigin(origins = "*")
public class TestController {
    
    @Autowired(required = false)
    private com.ecommerce.service.ReviewService reviewService;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @GetMapping("/reviews")
    public ResponseEntity<?> testReviews() {
        Map<String, Object> response = new HashMap<>();
        
        if (reviewService != null) {
            response.put("success", true);
            response.put("message", "ReviewService 已正确注入");
            response.put("serviceClass", reviewService.getClass().getName());
        } else {
            response.put("success", false);
            response.put("message", "ReviewService 注入失败");
        }
        
        return ResponseEntity.ok(response);
    }
    
    @GetMapping("/database")
    public ResponseEntity<?> testDatabase() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 检查product_review表是否存在
            List<Map<String, Object>> tables = jdbcTemplate.queryForList(
                "SHOW TABLES LIKE 'product_review'"
            );
            
            if (!tables.isEmpty()) {
                response.put("success", true);
                response.put("message", "product_review表存在");
                
                // 获取表结构
                List<Map<String, Object>> columns = jdbcTemplate.queryForList(
                    "DESCRIBE product_review"
                );
                response.put("columns", columns);
                
                // 获取记录数
                Integer count = jdbcTemplate.queryForObject(
                    "SELECT COUNT(*) FROM product_review", Integer.class
                );
                response.put("recordCount", count);
                
            } else {
                response.put("success", false);
                response.put("message", "product_review表不存在");
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "数据库连接失败: " + e.getMessage());
            response.put("error", e.toString());
        }
        
        return ResponseEntity.ok(response);
    }
    
    @GetMapping("/ping")
    public ResponseEntity<?> ping() {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "pong");
        response.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.ok(response);
    }
} 